import { useState, useEffect } from 'react';
import { useNavigate, Navigate } from 'react-router-dom';
import WechatLogin from '../components/WechatLogin';
import { wxAuthConfig } from '../config';
import '../pages/Login.css';
import { useAuth } from '../context/AuthContext';
import api from '../utils/api';
import { testCORS } from '../utils/debug';

export default function LoginPage() {
  const [phone, setPhone] = useState('');
  const [password, setPassword] = useState('');
  const [smsCode, setSmsCode] = useState(''); 
  const [countdown, setCountdown] = useState(0); 
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [debugInfo, setDebugInfo] = useState('');
  const navigate = useNavigate();
  const { user, login, loading: authLoading } = useAuth();
  
  // 如果用户已登录，直接重定向到首页
  if (user && !authLoading) {
    return <Navigate to="/" replace />;
  }

  const handleSubmit = async (e) => {
    e.preventDefault();
    
    setError('');
    setDebugInfo('');
    setLoading(true);
    
    try {
      // 添加详细的调试信息
      const debugStart = `开始登录请求 - ${new Date().toISOString()}\n`;
      setDebugInfo(debugStart);
      
      console.log('开始登录请求:', { phone });
      
      // 使用axios实例尝试请求
      console.log('尝试使用axios实例请求...');
      
      // 创建请求配置
      const requestConfig = {
        url: '/user/login',
        method: 'POST',
        data: {
          loginType: 1,
          phone: phone,
          password: password, // 添加密码字段
        },
        headers: {
          'Content-Type': 'application/json',
        }
      };
      
      // 记录请求配置
      const requestDebug = `请求配置:\n${JSON.stringify(requestConfig, null, 2)}\n`;
      setDebugInfo(prev => prev + requestDebug);
      console.log('请求配置:', requestConfig);
      
      // 发送请求
      const response = await api(requestConfig);
      
      // 记录响应
      const responseDebug = `响应:\n${JSON.stringify(response.data, null, 2)}\n`;
      setDebugInfo(prev => prev + responseDebug);
      console.log('登录响应:', response.data);
      
      // 处理响应
      if (response.data && (response.data.code === '200' || response.data.code === 200)) {
        const userData = response.data.data;
        
        // 记录登录成功
        console.log('登录成功，用户数据:', userData);
        setDebugInfo(prev => prev + '登录成功，正在跳转...\n');
        
        // 保存用户信息到localStorage
        localStorage.setItem('user', JSON.stringify(userData));
        
        // 更新认证上下文
        login(userData);
        
        // 跳转到主页
        navigate('/');
      } else {
        // 处理业务逻辑错误
        const errorMessage = response.data.message || '登录失败，请稍后再试';
        setError(errorMessage);
        setDebugInfo(prev => prev + `业务错误: ${errorMessage}\n`);
      }
    } catch (error) {
      console.error('登录失败:', error);
      
      let errorMessage = '登录失败: ' + error.message;
      let debugError = `错误: ${error.message}\n`;
      
      // 添加更详细的错误信息
      if (error.response) {
        errorMessage += ` (${error.response.status})`;
        debugError += `状态码: ${error.response.status}\n`;
        
        if (error.response.data) {
          debugError += `响应数据: ${JSON.stringify(error.response.data, null, 2)}\n`;
        }
      } else if (error.request) {
        // 请求已发送但没有收到响应
        debugError += `未收到响应\n请求: ${JSON.stringify(error.request, null, 2)}\n`;
      }
      
      setError(errorMessage);
      setDebugInfo(prev => prev + debugError);
    } finally {
      setLoading(false);
      setDebugInfo(prev => prev + `请求结束 - ${new Date().toISOString()}\n`);
    }
  };

  const sendSmsCode = async () => { 
    if (!/^1[3-9]\d{9}$/.test(phone)) return;
    setCountdown(60);
    const timer = setInterval(() => {
      setCountdown((prev) => (prev > 0 ? prev - 1 : 0));
    }, 1000);
    await api.post('/api/sms/send', { phone });
  };

  const handleTestCORS = async () => {
    setDebugInfo('正在测试CORS配置...');
    try {
      // 使用相对路径，让代理处理
      const result = await testCORS('/user/login');
      setDebugInfo(JSON.stringify(result, null, 2));
    } catch (error) {
      setDebugInfo(`测试失败: ${error.message}`);
    }
  };

  return (
    <div className="login-container">
      <div className="login-box">
        <h2>项目管理系统登录</h2>
        
        {/* 手机号登录表单 */}
        <form onSubmit={handleSubmit}>
          <div className="form-group">
            <input
              type="tel"
              placeholder="手机号"
              pattern="1[3-9]\d{9}"
              required
              value={phone}
              onChange={(e) => setPhone(e.target.value)}
            />
          </div>
          <div className="form-group">
            <input
              type="password"
              placeholder="密码"
              minLength="6"
              required
              value={password}
              onChange={(e) => setPassword(e.target.value)}
            />
          </div>
          <div className="verification-code-container">
            <input
              type="text"
              placeholder="请输入验证码"
              className="verification-code-input"
            />
            <span className="verification-code-text" onClick={sendSmsCode}  >{countdown > 0 ? `${countdown}秒后重试` : '发送验证码'}</span>
          </div>
          {error && <div className="error-message">{error}</div>}
          <button type="submit" className="login-btn" disabled={loading}>
            {loading ? '登录中...' : '登录'}
          </button>
        </form>

        {/* 调试信息 */}
        {process.env.NODE_ENV === 'development' && (
          <div className="debug-section">
            <button type="button" onClick={handleTestCORS} className="debug-btn">
              测试CORS配置
            </button>
            {debugInfo && (
              <pre className="debug-info">
                {debugInfo}
              </pre>
            )}
          </div>
        )}
        
        {/* 微信登录组件 */}
        <div className="social-login">
          <p className="divider">或使用第三方登录</p>
          <WechatLogin />
        </div>
      </div>
    </div>
  );
}
